# coding=utf-8

from app import mail_sender
from app.models import EmailStatus
from config import BaseConfig
from .. import db

from threading import Thread
from flask import app, current_app
from flask_mail import  Message
import smtplib



def send_email(uid,to,subject,template,imgs,**kwargs):
    msg = Message(subject,sender=BaseConfig.MAIL_USERNAME,recipients=[to],charset='gbk')
    msg.html = template
    for i in imgs:
        a1 = i.get('src').split('/')[-2:]
        a2 = a1[0] + r'\\' + a1[1]
        a3 = i.get('src').split('/')[-1:][0]
        a4 = i.get('cid')
        with current_app.open_resource("..\\static\\upload\\image\\"+a2) as fp:
            msg.attach(a3, "image/jpg", fp.read(), headers=[('ConTent-Id',a4)])
    send_async_email(uid,msg,current_app._get_current_object())
    return "ok"

def async(f):
    def wrapper(*args, **kwargs):
        try:
            thr = Thread(target=f, args=args, kwargs=kwargs)
            thr.start()
            emailstatus = EmailStatus.query.filter_by(uniquenum=args[0]).first()
            emailstatus.status = u'邮件正在发送'
            db.session.commit()
        except :
            emailstatus = EmailStatus.query.filter_by(uniquenum=args[0]).first()
            emailstatus.status = u'邮件发送失败'
            db.session.commit()
    return wrapper

@async
def send_async_email(uid,msg,capp):
    with capp.app_context():
        mail_sender.send(msg)
    return u'成功'


# 验证SMTP服务器是否可用
def user_auth():
    try:
        s = smtplib.SMTP()
        if BaseConfig.MAIL_USERNAME and BaseConfig.MAIL_PASSWORD:
            s.connect(BaseConfig.MAIL_SERVER, BaseConfig.MAIL_PORT)
            code_message = s.login(BaseConfig.MAIL_USERNAME, BaseConfig.MAIL_PASSWORD)
            s.close()
            return True
        else:
            try:
                s.connect(BaseConfig.MAIL_SERVER, BaseConfig.MAIL_PORT)
                s.ehlo()
                if s.has_extn('auth'):
                    return False
                else:
                    return True
            except:
                return False
            finally:
                s.close()
    except Exception as e:
        return False